define(['moment'
        ,'module/moduleB/program/B02/B0202/B0202Service'
        ,'module/moduleB/program/B02/B0203/B0203Service'
        ,'module/moduleB/program/B02/B0204/B0204Service'
        ,'module/moduleB/program/B02/B0205/B0205Service'
        ,'module/moduleWIP/program/B02/B0206/B0206Service'
        ,'module/moduleB/program/B02/B0207/B0207Service'
        ,'module/moduleB/program/B02/B0208/B0208Service'
        ,'module/moduleB/program/B02/B0209/B0209Service'
        ,'module/moduleB/program/B02/B0210/B0210Service'
        ,'module/moduleB/program/B02/B0211/B0211Service'
        ,'module/moduleB/program/B02/B0212/B0212Service'
        ,'module/moduleB/program/B02/B0213/B0213Service'
        ,'module/moduleB/program/B02/B0214_F/B0214_FService'
        ,'module/moduleB/program/B02/B0218/B0218Service'
        ,'module/moduleB/program/B02/B0219/B0219Service'
        ,'module/moduleB/program/B02/B0220/B0220Service'
        ,'module/moduleB/program/B02/B0221/B0221Service'
        ,'module/moduleB/program/B02/B0222/B0222Service'
        ,'module/moduleA/program/A04/A0401/A0401Service'
        ,'module/moduleA/program/A04/A0402/A0402Service'
        ,'module/moduleB/program/B02/B0223/B0223Service'
        ,'module/moduleWIP/program/B02/B0225/B0225Service'
        ,'module/moduleB/program/B02/B0226/B0226Service'
        ,'module/moduleB/program/B02/B0230/B0230Service'
        ,'module/moduleE/program/E02/E02Service'
        ,'module/system/service/WatchDogService'
        ,'module/system/program/password/password'
], function (moment) {
    return ['$state','$scope', '$filter', '$stateParams', 'config', 'MMWService','$mdDialog', '$timeout',
            'B0202Service',
            'B0203Service',
            'B0204Service',
            'B0205Service',
            'B0206Service',
            'B0207Service',
            'B0208Service',
            'B0209Service',
            'B0210Service',
            'B0211Service',
            'B0212Service',
            'B0213Service',
            'B0214_FService',
            'B0218Service',
            'B0219Service',
            'B0220Service',
            'B0221Service',
            'B0222Service',
            'A0401Service',
            'A0402Service',
            'B0223Service',
            'B0225Service',
            'B0226Service',
            'B0230Service',
            'E02Service',
            'WatchDogService',
            'PasswordService',
    function ($state,$scope, $filter, $stateParams, config, $MMWService,$mdDialog, $timeout
            ,$B0202Service
            ,$B0203Service
            ,$B0204Service
            ,$B0205Service
            ,$B0206Service
            ,$B0207Service
            ,$B0208Service
            ,$B0209Service
            ,$B0210Service
            ,$B0211Service
            ,$B0212Service
            ,$B0213Service
            ,$B0214_FService
            ,$B0218Service
            ,$B0219Service
            ,$B0220Service
            ,$B0221Service
            ,$B0222Service
            ,$A0401Service
            ,$A0402Service
            ,$B0223Service
            ,$B0225Service
            ,$B0226Service
            ,$B0230Service
            ,$E02Service
            ,$WatchDogService
            ,$PasswordService
    ) {
        $scope.areaItem = {};     //現在選擇的生產區域
        $scope.equipmentList = [];//區域內的機台列表
        //$scope.equipmentStatusList = []; //紀錄機台列表的內容
        $scope.dashboard={};      //儀錶板物件
        $scope.machineItem = {};
        $scope.workLogFilter = {plot_no:'', status:''};
        //$scope.plotItem = {};
        $scope.init = function(){
            $scope.menuClick = function(item){
                var programName = item.name;
                if (programName == 'B0202') {
                    var tempEquipmentList = [];
                    $scope.equipmentList.forEach(function(equipment){
                        if($scope.dashboard.machineStatusPlus.machineStatus[equipment.machine_no].isSelect){
                            //檢查此機台是否能上下工，可以的話將資料加入content.employeewrokset
                            //不行的話則回傳錯誤訊息
                            tempEquipmentList.push(equipment);
                        }
                    });
                    if(tempEquipmentList.length == 0){
                        tempEquipmentList.push($scope.machineItem);
                    }

                    $B0202Service.init(tempEquipmentList, 'machine', function(){
                        dog.bark();
                    });

                } else if (programName == 'B0203') {
                    var tempEquipmentList = [];
                    $scope.equipmentList.forEach(function(equipment){
                        if($scope.dashboard.machineStatusPlus.machineStatus[equipment.machine_no].isSelect){
                            //檢查此機台是否能上下工，可以的話將資料加入content.employeewrokset
                            //不行的話則回傳錯誤訊息
                            tempEquipmentList.push(equipment);
                        }
                    });
                    if(tempEquipmentList.length == 0){
                        tempEquipmentList.push($scope.machineItem);
                    }

                    $B0203Service.init(tempEquipmentList, undefined, 'machine', function(){
                        dog.bark();
                    });
                } else if (programName == 'B0210') {
                    $B0210Service.init($scope.machineItem, function(){
                        dog.bark();
                    });
                } else if (programName == 'B0211') {
                    $scope.machineItem.status = $scope.machineItem.machine_status;
                    $B0211Service.init($scope.machineItem, function(){
                        dog.bark();
                    });
                } else if (programName == 'B0220') {
                    $B0220Service.trenching($scope.machineItem.machine_no, function(){
                        dog.bark();
                    });
                } else if (programName == 'B0221') {
                    //設備稼動
                    $B0221Service.init({
                        machine : $scope.machineItem,
                        callback : function(){
                            dog.bark();
                        }
                    });
                } else if (programName == 'B0227') {
                    var tempEquipmentList = [];
                    $scope.equipmentList.forEach(function(equipment){
                        if($scope.dashboard.machineStatusPlus.machineStatus[equipment.machine_no].isSelect){
                            //檢查此機台是否能上下工，可以的話將資料加入content.employeewrokset
                            //不行的話則回傳錯誤訊息
                            tempEquipmentList.push(equipment);
                        }
                    });
                    if(tempEquipmentList.length == 0){
                        tempEquipmentList.push($scope.machineItem);
                    }
                    $B0203Service.employee_wrok_set_json({
                        machine_list : tempEquipmentList,
                        callback:function(){
                            dog.bark();
                        }
                    });
                }
            }

            $scope.dashboard = {
                operatorInfo : {
                    templateUrl : 'module/moduleB/program/dashboard/operatorInfo.html'
                },
                machineStatusPlus: {
                    templateUrl : 'module/moduleWIP/program/dashboard/machineStatusPlus.html',
                    mode : 'B0215',
                    machineStatus:{}
                },
                productInfo: {
                    templateUrl : 'module/moduleWIP/program/dashboard/productInfo.html'
                },
                workMaterial: {
                    templateUrl : 'module/moduleB/program/dashboard/workMaterial.html'
                },
                workLog : {
                    templateUrl : 'module/moduleB/program/dashboard/workLog.html',
                    statusList : ['Q', 'R', 'W', 'C', 'O', 'I']
                },
                accessory : {
                    templateUrl : 'module/moduleB/program/dashboard/accessory.html'
                }
            };
            if (typeof(Storage) !== 'undefined') {
                var panel_setting = JSON.parse(localStorage.getItem(config.appName + '_B0215_panel'));
                if(panel_setting){
                    $scope.dashboardPanel = panel_setting;
                }
            }
            $B0222Service.init($scope);
            $scope.PageConfig = {
                page : 0,
                page_count : 25
            };
            setMachineList($stateParams.machine_list);
            machine_working_info_get('1011', function(){
                $WatchDogService.startWatch(dog, true);
            });
        };

        function setMachineList(machine_list){
            machine_list.forEach(function(machine){
                if(!$scope.dashboard.machineStatusPlus.machineStatus[machine.machine_no])
                    $scope.dashboard.machineStatusPlus.machineStatus[machine.machine_no] = {isSelect:false};
            });
            $scope.dashboard.machineStatusPlus.machineList = $scope.equipmentList = machine_list;

            if(!$scope.dashboard.machineStatusPlus.selectMachine){
                $scope.machineItem = $scope.equipmentList[0];
                $scope.dashboard.machineStatusPlus.selectMachine = $scope.machineItem;

                /*
                20181005 modify by Dustdusk for M#51151: 改由後台處理，不再帶出machine_type為line的
                var isLine = ($scope.machineItem.machine_type == 'LINE')
                $scope.$root.menuList.forEach(function(menuItem){
                    if(menuItem.name == 'B0210' || menuItem.name == 'B0211'){
                        menuItem.disabled = isLine;
                    }
                });
                */
            }
        }

        //判斷機台是否有在我的最愛機台列表裡面
        function checkMachine(){
            var isIn = false;
            $scope.dashboard.machineStatusPlus.machineList.forEach(function(machine){
                if($scope.machineItem.machine_no == machine.machine_no){
                    $scope.machineItem = machine;
                    isIn = true;
                }
            });

            return isIn;
        }

        $scope.back = function(){
            $scope.disconnection = false;
            if(refresh_timer != undefined){
                $timeout.cancel(refresh_timer);
                refresh_timer = undefined;
            }
            $WatchDogService.stopWatch();
            //$scope.$root.hideMenu();
            $scope.$root.changeProgram('home', true);
        }

        //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
        var refresh_timer;
        function ErrorHandler(msg, isShowLoading, callback){
            $scope.$root.showAlert(msg);
            if(!isShowLoading){
                $scope.disconnection = true;
                $scope.refresh =  function(){
                    $scope.disconnection = false;
                    $timeout.cancel(refresh_timer);
                    refresh_timer = undefined;
                    callback();
                };
                if(refresh_timer == undefined){
                    refresh_timer = $timeout(function(){
                        $scope.refresh();
                    }, config.setting.RefreshTime*1000);
                }
            }
        }

        //我的最愛機台資訊取得
        function favourite_machine_info_get(feedback, isShowLoading) {
            var content = {
                master_no:config.setting.OperatingArea,
                master_type:'0',
                get_employee_data:'Y'
            };
            //20180518 modify by 李栋 for mantis#0047058
            $MMWService.sendToSMESServer({
                uri: 'tcSMES.clsSMES.favourite_machine_info_get_implement_json',
                content : content,
                success : function(data){
                    //根據第一筆機台取出設備加工資訊
                    // if(data.favourite_machine_info_get.length > 0){
                    if(data.query_restult.length > 0){

                        // setMachineList(data.favourite_machine_info_get);
                        setMachineList(data.query_restult);
                        if(!checkMachine()){
                            $scope.machineItem = $scope.equipmentList[0];
                            $scope.dashboard.machineStatusPlus.selectMachine = $scope.machineItem;
                        }
                        machine_working_info_get('1011', feedback, isShowLoading);
                    } else if(feedback){
                        feedback();
                    }
                },
                error: function(data){
                    //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一次
                    //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
                    ErrorHandler(data.Exception, isShowLoading, function(){
                        favourite_machine_info_get(feedback, isShowLoading);
                    });
                },
                netError: function(msg){
                    //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一次
                    //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
                    ErrorHandler(msg, isShowLoading, function(){
                        favourite_machine_info_get(feedback, isShowLoading);
                    });
                }
            }, isShowLoading);
        }

        //設備加工資訊取得
        function machine_working_info_get(data_type, feedback, isShowLoading)  {
            var content = {
                machine_no: $scope.machineItem.machine_no,
                data_type : data_type
            }

            //20180518 modify by 李栋 for mantis#0046663
            $MMWService.sendToSMESServer({
                uri: 'tcSMES_MachineWorkingInfoGet.clsSMES.machine_working_info_get_json',
                content : content,
                success : function(data){
                    $scope.dashboard.workLog.production_info_detail = data.machine_production_info_detail; //今日生產任務
                    $scope.dashboard.workMaterial.materials_detail = data.machine_materials_detail;  //上料資訊
                    try{
                        //$scope.$root.loadMenu();
                        machine_accessory_map_get(feedback, isShowLoading);
                    }catch(e){}
                },
                error: function(data){
                    //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一次
                    //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
                    ErrorHandler(data.Exception, isShowLoading, function(){
                        machine_working_info_get(data_type, feedback, isShowLoading);
                    });
                },
                netError: function(msg){
                    //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一次
                    //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
                    ErrorHandler(msg, isShowLoading, function(){
                        machine_working_info_get(data_type, feedback, isShowLoading);
                    });
                }
            }, isShowLoading);
        }

        function machine_accessory_map_get(feedback, isShowLoading){
            var content = {
                machine_no: $scope.machineItem.machine_no,
                is_line : '0'
            };

            //20180605 modify by 李栋 for mantis#0047557
            $MMWService.sendToSMESServer({
                uri: 'tcSMES.clsAccessory.machine_accessory_map_get_json',
                content : content,
                success : function(data){
                    $scope.dashboard.accessory.accessory_detail = data.accessory_detail;
                    try{
                        //$scope.$root.loadMenu();
                        checkLotInfo(feedback, isShowLoading);
                        //if(feedback)
                        //    feedback();
                    }catch(e){ console.log(e);}
                },
                error: function(data){
                    //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一次
                    //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
                    ErrorHandler(data.Exception, isShowLoading, function(){
                        machine_accessory_map_get(feedback, isShowLoading);
                    });
                },
                netError: function(msg){
                    //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一次
                    //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
                    ErrorHandler(msg, isShowLoading, function(){
                        machine_accessory_map_get(feedback, isShowLoading);
                    });
                }
            }, isShowLoading);
        }

        function checkLotInfo(callback, isShowLoading){
            if($scope.dashboard.workLog.production_info_detail.length > 0){
                if(!$scope.plotItem){
                    $scope.plotItem = $scope.dashboard.workLog.production_info_detail[0];
                }
                lotinfo_get($scope.plotItem, callback, isShowLoading);
            } else {
                $scope.dashboard.productInfo.item_code = '';
                $scope.dashboard.productInfo.wo_no = '';
                $scope.dashboard.productInfo.plot_no = '';
                $scope.dashboard.productInfo.qty = '';
                $scope.dashboard.productInfo.OutputQty = '';
                $scope.dashboard.productInfo.ScrapQty = '';
                $scope.dashboard.productInfo.GoodQty = '';
                $scope.dashboard.productInfo.reached_rate = '';
                $scope.dashboard.productInfo.next_op_no = '';
                $scope.dashboard.productInfo.flow_chart_url = '';
                if(callback)
                    callback();
            }
        }
        var reload_time = 0;
        function lotinfo_get(plotItem, callback, isShowLoading){
            var content = {
                LotNo : plotItem.plot_no,
                OPNo : plotItem.op_no
            };
            $MMWService.sendToSMESServer({
                uri : 'tcSMES.LotData.lotinfo_get',
                content : content,
                success : function(data){
                    reload_time = 0; //清除取得紀錄
                    $scope.dashboard.productInfo.item_code = data.ProductNo;
                    $scope.dashboard.productInfo.wo_no = data.MONo;
                    $scope.dashboard.productInfo.plot_no = data.LotNo;
                    $scope.dashboard.productInfo.qty = data.CurQTY;
                    $scope.dashboard.productInfo.OutputQty = data.OutputQty;
                    $scope.dashboard.productInfo.ScrapQty = data.ScrapQty;
                    $scope.dashboard.productInfo.GoodQty = data.GoodQty;
                    $scope.dashboard.productInfo.reached_rate = data.TodayArriveRate + '%';
                    $scope.dashboard.productInfo.next_op_no = data.next_op_no;
                    $scope.dashboard.productInfo.flow_chart_url = data.flow_chart_url;
                    if(callback)
                        callback();
                },
                error: function(data){
                    //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一次
                    if(isShowLoading == false){
                        reload_time++;
                        if(reload_time<2){
                            $scope.plotItem = undefined;
                            checkLotInfo(callback, isShowLoading);
                        } else {
                            //$scope.$root.showAlert(data.Exception, function(){
                            $scope.plotItem = undefined;
                            if(callback)
                                callback();
                            //});
                        }
                    } else {
                        $scope.$root.showAlert(data.Exception);
                    }
                },
                netError: function(msg){
                    //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一次
                    //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
                    ErrorHandler(msg, isShowLoading, function(){
                        lotinfo_get(plotItem, callback, isShowLoading);
                    });
                }
            });
        }

        var dog = {
            bark:function dog(feed, next){
                //使用favourite.machine.info.get取得我的最愛機台
                //取得設備加工資訊
                favourite_machine_info_get(next, next == undefined);
            }
        }
/****DialogList*************************************************************************************************************************************/
        var dialogList = [
             //上料
            {name: $filter('translate')('B0204.menuTitle'),status:['Q', 'R', 'W'], programName : 'B0204',
                init : function(){
                    $B0204Service.init($scope.machineItem, $scope.plotItem, 'machine', function(){
                        dog.bark();
                    });
                }},
            //標籤列印
            {name: $filter('translate')('B0230.menuTitle'),status:['Q', 'R', 'W', 'C'], programName : 'B0230',
                init : function(){
                    $B0230Service.init({plotItem:$scope.plotItem});
                }},
            // 進站報工
            // 20170511 modify by Dustdusk for 調整進站報工的方式
            {name: $filter('translate')('B0205.menuTitle'), status:['Q', 'B'], programName : 'B0205',
                init : function(status){
                    if(status == 'Q'){
                        $B0205Service.init($scope.machineItem , $scope.plotItem, 'machine', function(){
                            dog.bark();
                        });
                    } else if(status == 'B'){
                        var plotInfo = angular.merge({}, $scope.plotItem);
                    $B0205Service.SMES_PlotCheckInProcess({
                            machine_no:$scope.machineItem.machine_no,
                            plotInfo : plotInfo,
                            feedback : function(){
                                element_plot_no.focus();
                                dog.bark();
                            }
                        });
                    }
                }},
            //出站報工
            {name: $filter('translate')('B0206.menuTitle'), status:['R'], programName : 'B0206',
                init : function(){
                    $B0206Service.init($scope.machineItem,$scope.plotItem, 'machine', 'B0215', function(){
                        dog.bark();
                    });
                }},
            //批次進站
            {name: $filter('translate')('B0218.menuTitle'), status: ['Q'], programName : 'B0218',
                init : function(){
                    $B0218Service.init($scope.plotItem,$scope.machineItem.machine_no, 'B0215', function(){
                        dog.bark();
                    });
                }},
            //批次出站
            {name: $filter('translate')('B0219.menuTitle'), status: ['R'], programName : 'B0219',
                init : function(){
                    $B0219Service.init($scope.plotItem,$scope.machineItem.machine_no, 'B0215', function(){
                        dog.bark();
                    });
                }},
            //首件檢查
            {name: $filter('translate')('B0207.menuTitle_0'), status: ['Q', 'R', 'W'], programName : 'B0207',
                init : function(){
                    $B0207Service.init({
                        plotItem:$scope.plotItem,
                        machine_no:$scope.machineItem.machine_no,
                        area_no:'',
                        type: '0',
                        feedback:function(){
                            dog.bark();
                        }
                    });
                }},
            //巡檢
            {name: $filter('translate')('B0207.menuTitle_2'), status: ['Q', 'R', 'W'], programName : 'B0207',
                init : function(){
                    $B0207Service.init({
                        plotItem:$scope.plotItem,
                        machine_no:$scope.machineItem.machine_no,
                        area_no:'',
                        type: '2',
                        feedback:function(){
                            dog.bark();
                        }
                    });
                }},
            //暫停
            {name: $filter('translate')('B0208.menuTitle'), status: ['Q', 'R'], programName : 'B0208',
                init : function(){
                    $B0208Service.init({
                        machine_no: $scope.machineItem.machine_no,
                        plotItem: $scope.plotItem,
                        feedback: function(){
                            dog.bark();
                        }
                    });
                }},
             //解除暫停
            {name: $filter('translate')('B0209.menuTitle'), status: ['W'], programName : 'B0209',
                init : function(){
                    $B0209Service.init({
                        machine_no: $scope.machineItem.machine_no,
                        plotItem: $scope.plotItem,
                        feedback: function(){
                            dog.bark();
                        }
                    });
                }},
            //ESOP
            {name: $filter('translate')('B0212.menuTitle'), status: ['Q','R','C','W','P'], programName : 'B0212',
                init : function(){
                    $B0212Service.init($scope.plotItem);
                }},
            //分批作業
            {name: $filter('translate')('A0401.menuTitle'), status: ['Q','R'], programName : 'A0401',
                init : function(){
                    $A0401Service.init({
                        plotItem : $scope.plotItem,
                        feedback : function(){
                            dog.bark();
                        }
                    });
                }},
            //併批作業
            {name: $filter('translate')('A0402.menuTitle'), status: ['Q','R'], programName : 'A0402',
                init : function(){
                    $A0402Service.init({
                        plotItem : $scope.plotItem,
                        feedback : function(){
                            dog.bark();
                        }
                    });
                }},
            //重工
            {name: $filter('translate')('B0213.menuTitle'), status: ['Q','R'], programName : 'B0213',
                init : function(){
                    $B0213Service.init({
                        machine_no : $scope.machineItem.machine_no,
                        plot_detail : [$scope.plotItem],
                        feedback : function(){
                            dog.bark();
                        }
                    });
                }},
            //產品變更
            {name: $filter('translate')('B0223.menuTitle'), status: ['Q','R','W','C'], programName : 'B0223',
                init : function(){
                    $B0223Service.init({
                        plotItem : $scope.plotItem,
                        feedback : function(){
                            dog.bark();
                        }
                    });
                }},
                //報工還原
            {name: $filter('translate')('B0225.menuTitle'), status: ['Q','R'], programName : 'B0225',
                init : function(){
                    $B0225Service.init({
                        machine_no : $scope.machineItem.machine_no,
                        plotItem : $scope.plotItem,
                        callback : function(){
                            dog.bark();
                        }
                    });
                }},
            //設備變更
            {name: $filter('translate')('B0226.menuTitle'), status: ['R'], programName : 'B0226',
                init : function(){
                    $B0226Service.init({
                        machine_no : $scope.machineItem.machine_no,
                        plotItem : $scope.plotItem,
                        callback : function(){
                            dog.bark();
                        }
                    });
                }},
            //設備點檢
            {name: $filter('translate')('B0210.menuTitle'), status: ['M'], programName : 'B0210',
                init : function(){
                    $B0210Service.init($scope.machineItem, function(){
                        dog.bark();
                    });
                }},
            //稼動變更
            {name: $filter('translate')('B0211.menuTitle'), status: ['M'], programName : 'B0211',
                init : function(){
                    $B0211Service.init($scope.machineItem, function(){
                        dog.bark();
                    });
                }},
            {name: $filter('translate')('B0201.X'), status: [], programName : '',}
        ];


        $scope.openToolBar=function (status) {
            $scope.workLogStatus = status;
            $mdDialog.dialog(
                'module/moduleB/program/B02/B0201/ToolBar.tmp.html',
                ToolBarController
            );
        }

        function ToolBarController(dialog) {
            return {
                dialogList: dialogList,
                buttonAction:function(button){
                    this.hide();
                    if(button.init){
                        button.init($scope.workLogStatus);
                    }
                },
                btnFilter:function(button){
                    if(button.status.length == 0){
                        return button;
                    } else {
                        if(!config.cache.permissions || config.cache.permissions.indexOf(button.programName)!=-1){
                            if($scope.machineItem.machine_status ==0 || $scope.machineItem.machine_status ==1){
                                if(button.status.indexOf($scope.workLogStatus) != -1){
                                    if(button.programName == 'B0223'){
                                        if($scope.plotItem && $scope.plotItem.product_change == '2'){
                                            return button;
                                        }
                                    } else {
                                        return button;
                                    }
                                }
                            } else {
                                if(button.programName == 'B0212'){
                                    return button;
                                }
                            }
                        }
                    }
                },
                background:{
                    class:['toolbar-background'],
                    click: function(){
                        dialog.hide();
                    }
                }
            }
        }
/****Dashboard**************************************************************************************************************************************/
        var statusOrder = {'C': 0, 'R': 1, 'W': 2, 'Q': 3};
        $scope.dashboardPanel = ['machineStatusPlus','workMaterial','productInfo', 'workLog'];
        $scope.isInnerContentHide = false;

        $scope.togglePanel = function(sectionName){
            var target = $scope.dashboard[sectionName];
            if(sectionName == 'workMaterial' || sectionName == 'productInfo' || sectionName == 'accessory'){
                $scope.isInnerContentHide = !$scope.isInnerContentHide;

            } else {
                target.isContentHide = !target.isContentHide;
            }
        };


        //今日生產任務- C隱藏，R置頂
        var statusCount = 0;
        $scope.countStatus = function(item){
            if(item.status == 'C')
                statusCount++;
        }
        $scope.goStatusR = function(){
            $timeout(function(){
                var workLogList = document.getElementsByClassName('kmi-list__workLog')[0];
                //angular.element(document).find('.workLog .kmi-list__row-content');
                workLogList.scrollTop = (+statusCount)*46+2;
                //console.log(workLogList.scrollTop);
            });
        };

        /***
         * 機台狀態列表
         * 0:RUN(加工) - 綠
         * 1:IDLE(閒置) - 黃
         * 2:DOWN(故障) - 紅
         * 3:SETUP(設置)
         * 4:SHUTDOWN(停機、關機)
         * 5:暫停(201609新增)
         *
         **/
        $scope.machineStatus = function (status) {
            switch (status){
                case '0':
                    return 'green';
                case '1':
                    return 'yellow';
                case '2':
                    return 'red';
            }
            return '';
        };

        $scope.changeMachine = function(machine){
            $scope.machineItem = machine;
            $scope.dashboard.machineStatusPlus.selectMachine = machine;
            $scope.plotItem = undefined;
            //$scope.openToolBar('M');
            /*
            20181005 modify by Dustdusk for M#51151: 改由後台處理，不再帶出machine_type為line的
            var isLine = ($scope.machineItem.machine_type == 'LINE');
            $scope.$root.menuList.forEach(function(menuItem){
                if(menuItem.name == 'B0210' || menuItem.name == 'B0211'){
                    menuItem.disabled = isLine;
                }
            });
            */
            $scope.PageConfig.page = 0;
            machine_working_info_get('1011');
        };

        $scope.getPlotInfo = function(plot, event){
            event.stopPropagation();
            $scope.plotItem = plot;
            lotinfo_get(plot, undefined, true);
        };

        $scope.clickPlot = function(plot, event){
            $scope.plotItem = plot;
            // 20210330 modify by 奕達 for M#90257
            lotinfo_get(plot, undefined, true);
            $scope.openToolBar(plot.status);
        };

        /***
        * 生產批物料是否投放
        * 20170425新增，is_materials= 0 顯示紅色，1 顯示綠色 和-1 不顯示顏色
        * 20171113 mantis#0041868:調整，is_materials= 0 顯示紅色，1 顯示橘色、2綠色 和-1 不顯示顏色
        */
       $scope.isMaterials = function(is_materials){
            switch (is_materials){
                case '0':
                    return 'red';
                case '1':
                    return 'yellow';
                case '2':
                    return 'green';
            }
            return '';
       };

        $scope.loadMyFavorites = function(event){
            event.stopPropagation();
            $PasswordService.init({
                mode:'confirm',
                feedback:function(){
                    $WatchDogService.stopWatch();
                    //$scope.$root.hideMenu();
                    $B0214_FService.init({
                        parent:'B0215',
                        next:'B0215',
                        master_no:config.setting.OperatingArea,
                        machine_list:$scope.equipmentList,
                        feedback: function(dialog){
                            dialog.hide();
                            $scope.plotItem = undefined;
                            dog.bark();
                        }
                    });
                }
            });
        };

        $scope.machineSelect = function(event, index,item){
            event.stopPropagation();
            var machine = $scope.dashboard.machineStatusPlus.machineStatus[item.machine_no]
            machine.isSelect = !machine.isSelect;
        };

        $scope.machineSelectAll = function(){
            $scope.dashboard.machineStatusPlus.selectAll = !$scope.dashboard.machineStatusPlus.selectAll;
            $scope.dashboard.machineStatusPlus.machineList.forEach(function(machine){
                $scope.dashboard.machineStatusPlus.machineStatus[machine.machine_no].isSelect = $scope.dashboard.machineStatusPlus.selectAll;
            });
        };

        $scope.workSet = function(event, machine){
            event.stopPropagation();
            $E02Service.init({
				stationMachine:{
                    parent:'B0215',
                    pdline_no:machine.machine_no,
                    employee_work_detail:machine.employee_work_detail
                },
				close:function(){
                    //dog.bark();
				},
				callback:function(callback, dialog){
                    favourite_machine_info_get(function(){
                        var temp = $filter('filter')($scope.dashboard['machineStatusPlus'].machineList, {machine_no:machine.machine_no});
                        if(temp && temp.length > 0){
                            dialog.stationMachine.employee_work_detail = temp[0].employee_work_detail;
                        } else {
                            dialog.close();
                        }
                    }, true);
				}
			});
        };

        $scope.changePanel = function(event, panelCode){
            event.stopPropagation();
            var panelList = [
                {panelCode : 'workMaterial', panelName: $filter('translate')('dashboard.workMaterial.title')},
                {panelCode : 'productInfo', panelName: $filter('translate')('dashboard.productInfo.title')},
                {panelCode : 'accessory', panelName: $filter('translate')('dashboard.accessory.title')}
            ];

            //$scope.dashboardPanel = ['operatorInfo','machineStatusPlus','workMaterial','productInfo', 'workLog'];
            $scope.$root.showSelect({
                title : $filter('translate')('common.msg.plz_select'),
                label : 'panelName',
                code : 'panelCode',
                selectCode : panelCode,
                list : panelList,
                confirm : function(item, dialog){
                    var now_panel_index = $scope.dashboardPanel.indexOf(panelCode);
                    var select_panel_index = $scope.dashboardPanel.indexOf(item.panelCode);
                    //當為-1時表示選擇的不再列表內，則不用做交換
                    if(select_panel_index != -1){
                        $scope.dashboardPanel[select_panel_index] = panelCode;
                    }
                    $scope.dashboardPanel[now_panel_index] = item.panelCode;
                    localStorage.setItem(config.appName + '_B0215_panel', JSON.stringify($scope.dashboardPanel));
                    dialog.hide();
                }
            });

        }

/*****************************************************************************************************************/
        var element_plot_no;
        input_plot_focus = true;
        //20170511 modify by Dustdusk for 新增barcode/QRcode輸入功能
        $scope.focusInputPlot = function(){
            element_plot_no = document.getElementById('input_plot');
            /*
            element_plot_no.addEventListener('blur', function(){
                if(input_plot_focus){
                    element_plot_no.focus();
                }
            });
            */
            element_plot_no.focus();
        }

        //barcode輸入
        $scope.input_plot_no = function(event){
            if(event.keyCode == 13){
                element_plot_no.blur();
                input_plot_no_callback();
            } else {
                $scope.dashboard['workLog'].barcode_plot_no = $scope.dashboard['workLog'].barcode_plot_no||'';
                if(event.key){
                    $scope.dashboard['workLog'].barcode_plot_no += event.key;
                } else {
                    $scope.dashboard['workLog'].barcode_plot_no += String.fromCharCode(event.keyCode);
                }
            }
        }

        //QRCode輸入
        $scope.qrcode_plot_no = function(){
            $scope.$root.OpenScanner({
                after : function(result){
                    $scope.dashboard['workLog'].barcode_plot_no = result.text;
                    input_plot_no_callback();
                },
                exception: function(){
                    //目前裝置無法使用相機
                    $scope.$root.showAlert($filter('translate')('B0214.showAlert.column3'));
                },
                orientation : 'landscape'
            });
        }

        function input_plot_no_callback(){
            //檢查輸入的對不對
            var barcode_plot_no = $scope.dashboard['workLog'].barcode_plot_no;
            var temp_plot_array = barcode_plot_no.split(';');
            $scope.dashboard['workLog'].barcode_plot_no = '';
            if(temp_plot_array.length == 2){
                var is_muilt = false, plotItem;
                $scope.dashboard['workLog'].production_info_detail.forEach(function(production_info){
                    if(barcode_plot_no == (production_info.plot_no + ';' + production_info.op_no)){
                        if(!plotItem){
                            plotItem = production_info;
                        } else if(plotItem.status != production_info.status){
                            is_muilt = true;
                        }
                    }
                });

                if(!plotItem){
                    //刷入的生產批 + 作業站並不包含在本作業中，請確定刷入的條碼是否正確或確認選定的作業機台是否正確。
                    $scope.$root.showAlert(
                        $filter('translate')('B0214.showAlert.column4_1')+temp_plot_array[0]
                        + $filter('translate')('B0214.showAlert.column4_2')+temp_plot_array[1]
                        + $filter('translate')('B0214.showAlert.column4_3'),
                    function(){
                        element_plot_no.focus();
                    });
                } else {
                    $scope.plotItem = plotItem;

                    if(is_muilt){
                        //開氣泡選單
                        $scope.openToolBar('B');
                    } else if($scope.plotItem.status == 'Q'){
                        //直接進站
                        var plotInfo = angular.merge({}, $scope.plotItem);
                        $B0205Service.SMES_PlotCheckInProcess({
                            machine_no:$scope.machineItem.machine_no,
                            plotInfo : plotInfo,
                            feedback : function(){
                                element_plot_no.focus();
                                dog.bark();
                            }
                        });
                    } else if($scope.plotItem.status == 'R'){
                        $B0206Service.init($scope.machineItem, $scope.plotItem, 'machine', 'B0215', function(){
                            dog.bark();
                        });
                    } else {
                        //'生產批 XXXX 狀態為 O 無法進站或出站
                        $scope.$root.showAlert(
                            $filter('translate')('B0214.showAlert.column5_1')+temp_plot_array[1]
                            + $filter('translate')('B0214.showAlert.column5_2')+$scope.plotItem.status
                            + $filter('translate')('B0214.showAlert.column5_3'),
                        function(){
                            element_plot_no.focus();
                        });
                    }
                }
            } else {
                $scope.$root.showAlert($filter('translate')('B0214.showAlert.column6'), function(){
                    element_plot_no.focus();
                });
            }
        }

        $scope.openStatusFilter = function(){
            var statusList = [
                {display:$filter('translate')('dashboard.workLog.status.q'), code:'Q', isSelect:($scope.dashboard['workLog'].statusList.indexOf('Q')!=-1)},
                {display:$filter('translate')('dashboard.workLog.status.r'), code:'R', isSelect:($scope.dashboard['workLog'].statusList.indexOf('R')!=-1)},
                {display:$filter('translate')('dashboard.workLog.status.w'), code:'W', isSelect:($scope.dashboard['workLog'].statusList.indexOf('W')!=-1)},
                {display:$filter('translate')('dashboard.workLog.status.c'), code:'C', isSelect:($scope.dashboard['workLog'].statusList.indexOf('C')!=-1)},
                {display:$filter('translate')('dashboard.workLog.status.o'), code:'O', isSelect:($scope.dashboard['workLog'].statusList.indexOf('O')!=-1)},
                {display:$filter('translate')('dashboard.workLog.status.i'), code:'I', isSelect:($scope.dashboard['workLog'].statusList.indexOf('I')!=-1)}
            ];
            $scope.$root.showCheckList({
                label : 'display',
                code : 'code',
                order : '$index',
                list : statusList,
                confirm : function(checkList, dialog){
                    dialog.hide();
                    $scope.dashboard['workLog'].statusList = [];
                    checkList.forEach(function(temp){
                        if(temp.isSelect === true){
                            $scope.dashboard['workLog'].statusList.push(temp.code);
                        }
                    });
                }
            });
        };

        $scope.getPages = function(list, PageConfig, filterItem){
            if(list){
                var temp_list = list.filter(function(item, index, array){
                    var isOK = true,
                        keys = Object.keys(filterItem);
                    for(var i =0; i<keys.length;i++){
                        var key = keys[i];
                        if(isOK && item[key]!=null && filterItem[key] && filterItem[key]!=''){
                            if(item[key].indexOf(filterItem[key]) == -1){
                                isOK = false;
                                break;
                            }
                        }
                    }
                    //狀態過濾
                    if(isOK && $scope.dashboard['workLog'].statusList.indexOf(item.status) ==-1){
                        isOK = false;
                    }
                    return isOK;
                });
                if(PageConfig){
                    PageConfig.total_page = Math.ceil(temp_list.length/PageConfig.page_count);
                    if(PageConfig.page >= PageConfig.total_page){
                        PageConfig.page = 0;
                    }
                    var index = PageConfig.page*PageConfig.page_count;
                    return temp_list.slice(index, index+PageConfig.page_count);
                } else {
                    return temp_list;
                }
            } else {
                return list;
            }
        };
    }
];});
